#pragma once
#ifndef __COMM_HPP__
#define __COMM_HPP__



#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <cstring>
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>


using namespace std;


const char* pathname="/root/my_git/lesson26_shm";
const int proj_id=0x66;
const int defaultsize=4097;//单位是字节


string TuHex(key_t k)
{
    char buffer[1024];
    snprintf(buffer,sizeof(buffer),"%x",k);
    return buffer;
}

//获取key
key_t GetShyKeyorDie()
{
    key_t k=ftok(pathname,proj_id);
    if(k<0)
    {
        cerr<<"ftok error:"<<errno<<",error string:"<<strerror(errno)<<endl;
        exit(1);
    }
    return k;
}

//获取shmid
int CreatShmOrDie(key_t key,int size,int flag)
{
    int shmid=shmget(key,size,flag);
    if (shmid < 0)
    {
        cerr<<"shm error:"<<errno<<",error string:"<<strerror(errno)<<endl;
        exit(2);
    }
    return shmid;
}

//创建共享内存
int CreateShm(key_t key,int size)
{
    //IPC_CREAT:不存在就创建
    //IPC_EXCL:没有意义
    //TPC_CREAT|IPC_EXCL:不存在就创建，存在就出错
    return CreatShmOrDie(key,size,IPC_CREAT|IPC_EXCL|0666);
}

//获取共享内存
int GetShm(key_t key,int size)
{
    return CreatShmOrDie(key,size,IPC_CREAT);
}

//删除共享内存函数
void DeleteShm(int shmid)
{
    int n=shmctl(shmid,IPC_RMID,nullptr);
    if(n<0)
    {
        cerr<<"shmctl error"<<endl;
    }
    else
    {
        cout<<"shmctl delete shm success,shmid:"<<shmid<<endl;
    }
}

//显示shmid属性函数
void ShmDebug(int shmid)
{
    struct shmid_ds shmds;
    int n=shmctl(shmid,IPC_STAT,&shmds);
    if(n<0)
    {
        cerr<<"shmctl error"<<endl;
        return;
    }
    cout<<"shmds.shm_segsz:"<<shmds.shm_segsz<<endl;
    cout<<"shmds.shm_nattch:"<<shmds.shm_nattch<<endl;
    cout<<"shmds.shm_ctime:"<<shmds.shm_ctime<<endl;
    cout<<"shmds.shm_perm.__key:"<<shmds.shm_perm.__key<<endl;
}

//挂接函数
void* ShmAttach(int shmid)
{
    void* addr=shmat(shmid,nullptr,0);
    if((long long)addr==-1)//在64位下指针是8字节，而int为4字节
    {
        cerr<<"shmat error"<<endl;
        return nullptr;
    }
    return addr;
}

void ShmDetach(void* addr)
{
    int n=shmdt(addr);
    if(n<0)
    {
        cerr<<"shmdt error"<<endl;
        return;
    }
}



#endif